<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <script type="text/javascript" charset="utf-8" src="../../../../../../res_common/third/socket/sockjs.min.js"></script>
</head>
<body>
    Welcome<br/>
    <input id="text" type="text"/>
    <button onclick="oui.send()">发送消息</button>
    <hr/>
    <button onclick="oui.closeWebSocket()">关闭WebSocket连接</button>
    <hr/>
    <div id="message"></div>
</body>
<script type="text/javascript">
    var oui = {};
    oui.connectWebSocket = function(url){
        var websocket = null;
        if ('WebSocket' in window) {
            websocket = new WebSocket(url);
            oui._websocket = websocket;
        }else {
            websocket = new SockJS(url);
            oui._websocket = websocket;
        }

        oui.setMessageInnerHTML = function(msg){
            var msgDom = document.getElementById('message');
            var html =  msgDom.innerHTML;
            html +=msg;
            msgDom.innerHTML = html;
        };
        //连接发生错误的回调方法
        websocket.onerror = function () {
            oui.setMessageInnerHTML("WebSocket连接发生错误");
        };

        //连接成功建立的回调方法
        websocket.onopen = function () {
            oui.setMessageInnerHTML("WebSocket连接成功");
        };

        //接收到消息的回调方法
        websocket.onmessage = function (event) {
            oui.setMessageInnerHTML(event.data);
        };

        //连接关闭的回调方法
        websocket.onclose = function () {
            oui.setMessageInnerHTML("WebSocket连接关闭");
        };
        //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        window.onbeforeunload = function () {
            oui.closeWebSocket();
        };
        oui.send = function(){
            var message = document.getElementById('text').value;
            oui._websocket.send(message);
        };
        oui.closeWebSocket = function(){
            oui._websocket.close();
        };
    };
    window.oui = oui;
    /* 页面加载完成后处理***/
    window.onload = function(){
        oui.connectWebSocket(window.websocketUrl);//建立连接
    };
</script>





